<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :title="title + '入库'"
      :width="drawerWidth"
      @cancel="handleClose"
      :destroyOnClose="true"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="onSubmit"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="onSubmit" type="primary">确认</a-button>
        </div>
      </template>
      <div
        :style="{
          width: '100%',
          border: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
        }"
      >
        <a-spin :spinning="confirmLoading">
          <a-form-model ref="ruleForm" :model="model" :rules="rules">
            <a-tabs v-model="model.receiptType" @change="handleTabChange">
              <a-tab-pane
                :tab="item.dictName"
                v-for="item in receiptTypeOption"
                :key="item.id"
                :disabled="title == '编辑'"
              >
              </a-tab-pane>
            </a-tabs>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="入库单号"
                  hasFeedback
                  prop="acceptanceNum"
                >
                  <a-input
                    :disabled="title == '编辑'"
                    placeholder="请输入入库单号"
                    v-model.trim="model.acceptanceNum"
                  /> </a-form-model-item
              ></a-col>

              <a-col :span="12" v-if="model.receiptTypeName === '生产入库'">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="加工单"
                  hasFeedback
                  prop="worksheetId"
                >
                  <a-select
                    :disabled="title == '编辑'"
                    :open="false"
                    :defaultOpen="false"
                    mode="multiple"
                    :allowClear="true"
                    placeholder="请选择加工单"
                    v-model.trim="model.worksheetId"
                    @dropdownVisibleChange="
                      (open) =>
                        handleTableSelect(
                          open,
                          'worksheetId',
                          'tableOrderModal',
                          '加工单'
                        )
                    "
                    @change="
                      (value) => handleChange(value, 'worksheetId', orderModel)
                    "
                  >
                    <a-select-option
                      v-for="item in orderModel.tableOption"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.processNum }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item></a-col
              >
              <a-col :span="12" v-else>
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="商品"
                  hasFeedback
                  prop="goodsId"
                >
                  <a-select
                    :open="false"
                    :defaultOpen="false"
                    mode="multiple"
                    :allowClear="true"
                    placeholder="关联商品"
                    v-model.trim="model.goodsId"
                    :disabled="title == '编辑'"
                    @dropdownVisibleChange="
                      (open) =>
                        handleTableSelect(open, 'goodsId', 'tableModal', '商品')
                    "
                    @change="
                      (value) => handleChange(value, 'goodsId', goodModel)
                    "
                  >
                    <a-select-option
                      v-for="item in goodModel.tableOption"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.goodsName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="12">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="批号"
                  hasFeedback
                  prop="remarks"
                >
                  <a-input
                    placeholder="请输入批号"
                    v-model.trim="model.batchNum"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="备注"
                  hasFeedback
                  prop="remarks"
                >
                  <a-input
                    placeholder="请输入备注"
                    v-model.trim="model.remarks"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <!-- <a-col :span="12">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="加工单数量"
                  hasFeedback
                  prop="planAmount"
                >
                  <a-input
                    disabled
                    placeholder="请输入加工单数量"
                    v-model.trim="model.planAmount"
                  />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="12">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="商品编号"
                  hasFeedback
                  prop="goodsCode"
                >
                  <a-input
                    disabled
                    placeholder="请输入商品编号"
                    v-model.trim="model.goodsCode"
                  /> </a-form-model-item
              ></a-col>
              <a-col :span="12" v-if="model.receiptTypeName === '生产入库'">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="商品名称"
                  hasFeedback
                  prop="goodsName"
                >
                  <a-input
                    disabled
                    placeholder="请输入商品名称"
                    v-model.trim="model.goodsName"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="商品规格"
                  hasFeedback
                  prop="specifications"
                >
                  <a-input
                    disabled
                    placeholder="请输入商品规格"
                    v-model.trim="model.specifications"
                  /> </a-form-model-item
              ></a-col>

              <!-- 库位选择 -->

              <a-col
                :span="12"
                class="shelfBox"
                v-for="(item, index) in model.shelfIdAndGoodsQuantityVOList"
                :key="index"
              >
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  :label="`库位${index + 1}`"
                  hasFeedback
                  :rules="rules.shelfId"
                  :prop="`shelfIdAndGoodsQuantityVOList[${index}].shelfId`"
                >
                  <a-select
                    style="width:236px"
                    :open="false"
                    :defaultOpen="false"
                    :allowClear="true"
                    placeholder="请选择库位"
                    v-model.trim="item.shelfId"
                    @dropdownVisibleChange="
                      (open) => handleReciptSelect(open, index)
                    "
                    @change="handleReciptChange"
                  >
                    <a-select-option
                      v-for="item in shelfModel.tableOption"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="数量"
                  hasFeedback
                  :rules="rules.quantity"
                  :prop="`shelfIdAndGoodsQuantityVOList[${index}].quantity`"
                >
                  <a-input
                    style="width:236px"
                    placeholder="请输入数量"
                    v-model.trim="item.quantity"
                  />
                </a-form-model-item>
                <a-form-model-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-icon
                    v-if="
                      model.shelfIdAndGoodsQuantityVOList.length - 1 === index
                    "
                    type="plus-circle"
                    class="iconBox"
                    @click="handleCapacityAdd"
                  ></a-icon>
                  <a-icon
                    v-else
                    type="close"
                    class="iconBox"
                    @click="handleCapacityDelete(index)"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-spin>
      </div>
    </a-modal>
    <!-- 加工单生产计划选择 -->
    <TableSelectModal
      :columns="orderModel.columns"
      :replaceFields="orderModel.replaceFields"
      :tableKey="orderModel.tableKey"
      :name="orderModel.name"
      :code="orderModel.code"
      ref="tableOrderModal"
      @tableSelect="tableSelect"
    ></TableSelectModal>
    <!-- 库位选择 -->
    <ReceiptSelectModal ref="Receipt" @ReceiptSelect="ReceiptSelect" />
    <!-- 商品选择 -->
    <TableSelectModal
      :columns="goodModel.columns"
      :replaceFields="goodModel.replaceFields"
      :treeKey="goodModel.treeKey"
      :tableKey="goodModel.tableKey"
      :searchKey="goodModel.searchKey"
      :name="goodModel.name"
      :code="goodModel.code"
      :filename="goodModel.filename"
      ref="tableModal"
      @tableSelect="tableGoodSelect"
    ></TableSelectModal>
  </div>
</template>
<script>
import api from "@/api/apiServer";
import TableSelectModal from "@/components/TableSelectModal";
import { shelfModel, goodModel, orderModel } from "./tableConfig";
import ReceiptSelectModal from "./ReceiptSelectModal.vue";
export default {
  components: { TableSelectModal, ReceiptSelectModal },
  data() {
    return {
      title: "", // 标题
      visible: false, // 状态、
      drawerWidth: 1677, // 抽屉宽度
      model: {
        shelfIdAndGoodsQuantityVOList: [{ shelfId: undefined, quantity: null }],
      },
      wareHouseList: [],
      fieldNames: { label: "wareHouseName", value: "id", children: "children" },
      show: true, //根据菜单类型，动态显示隐藏表单元素
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      receiptTypeOption: [],
      disabled: false,
      inStockTime: "",
      shelfModel, // 库位
      goodModel, // 商品
      orderModel, // 商品
      current: 0,
    };
  },
  computed: {
    rules() {
      return {
        acceptanceNum: [
          { required: true, message: "请输入入库单号", trigger: "change" },
        ],
        shelfId: [
          { required: true, message: "请选择库位名称", trigger: "change" },
        ],
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        quantity: [
          { required: true, message: "请输入数量", trigger: "change" },
        ],
        receiptType: [
          { required: true, message: "请选择入库类型", trigger: "change" },
        ],
        worksheetId: [
          { required: true, message: "请选择加工单", trigger: "change" },
        ],
        amount: [
          { required: true, message: "请输入入库数量", trigger: "change" },
        ],
        inStockTime: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
      };
    },
  },

  mounted() {},
  methods: {
    handleTabChange(value) {
      this.model = Object.assign({});
      this.getWarehousingNumber();
      this.$set(this.model, "shelfIdAndGoodsQuantityVOList", [
        { shelfId: undefined, quantity: null },
      ]);
      this.$set(this.model, "receiptType", value);
      let obj = this.receiptTypeOption.find((item) => item.id === value);
      this.$set(this.model, "receiptTypeName", obj.dictName);
      if (this.model.receiptTypeName === "来料入库") {
        this.$refs.ruleForm.clearValidate("worksheetId");
        this.$refs.ruleForm.validateField("goodsId");
        this.$refs.ruleForm.clearValidate(
          `shelfIdAndGoodsQuantityVOList[${this.current}].shelfId`
        );
        this.$refs.ruleForm.clearValidate(
          `shelfIdAndGoodsQuantityVOList[${this.current}].quantity`
        );
      } else {
        this.$refs.ruleForm.clearValidate("goodsId");
        this.$refs.ruleForm.validateField("worksheetId");
        this.$refs.ruleForm.clearValidate(
          `shelfIdAndGoodsQuantityVOList[${this.current}].shelfId`
        );
        this.$refs.ruleForm.clearValidate(
          `shelfIdAndGoodsQuantityVOList[${this.current}].quantity`
        );
      }
    },
    handleCapacityAdd() {
      this.model.shelfIdAndGoodsQuantityVOList = [
        ...this.model.shelfIdAndGoodsQuantityVOList,
        { shelfId: undefined, quantity: null },
      ];
    },
    handleCapacityDelete(index) {
      if (this.model.shelfIdAndGoodsQuantityVOList.length === 1) {
        return;
      }
      this.model.shelfIdAndGoodsQuantityVOList = this.model.shelfIdAndGoodsQuantityVOList.filter(
        (item, i) => i != index
      );
    },
    // 查询入库单号
    async getWarehousingNumber() {
      const res = await api.WarehousingNumber();
      this.$set(this.model, "acceptanceNum", res.data);
    },
    // 获取入库类型数据源
    async getDictFindByCode(parentCode) {
      const res = await api.DictFindByCode({ parentCode });
      this.receiptTypeOption = res.data;
      if (this.model.receiptType == null) {
        this.$set(this.model, "receiptType", res.data[0].id);
        this.$set(this.model, "receiptTypeName", res.data[0].dictName);
      } else {
        let obj = this.receiptTypeOption.find(
          (item) => item.id === this.model.receiptType
        );
        this.$set(this.model, "receiptTypeName", obj.dictName);
        if (this.model.receiptTypeName == "生产入库") {
          this.getWorksheetList(this.model.worksheetId);
        }
      }
    },
    // 获取加工单数据
    async getWorksheetList(worksheetId) {
      const params = { worksheetId };
      const res = await api.WorkSelByProcessId(params);
      this.orderModel.tableOption = [res.data.detile];
    },
    // 选择器选择
    handleTableSelect(open, key, refName, name) {
      this.$refs[refName].title = name;
      this.$refs[refName].modalAdd();
      if (this.model[key]) {
        let arr = this.model[key].toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs[refName].selectedRowKeys = newArr;
        } else {
          this.$refs[refName].selectedRowKeys = [];
        }
      }
    },
    // 事件选择回调
    handleChange(value, key, model) {
      if (value.length > 0) {
        if (model.mode) {
          this.model[key] = value;
        } else {
          this.model[key] = value.toString();
        }
      } else {
        this.model[key] = value;
      }
    },
    // 处理选择组件的数据
    setData(result, tableOption, modelName, key) {
      this[modelName].tableOption = tableOption;
      if (modelName === "goodModel") {
        this.checkResult = result[0];
      }
      if (this[modelName].mode) {
        let arr = result.map((item) => {
          return item.id;
        });
        this.$set(this.model, key, arr);
      } else {
        this.$set(this.model, key, result[0].id);
      }
      this.$refs.ruleForm.clearValidate([key]);
    },
    // 商品选择
    tableGoodSelect(result, tableOption) {
      this.setData(result, tableOption, "goodModel", "goodsId");
      this.getCommodityList(result[0].id);
    },
    tableSelect(result, tableOption) {
      this.orderModel.tableOption = tableOption;
      let checkResult = result[0];
      if (checkResult) {
        this.$set(this.model, "worksheetId", checkResult.id);
        this.$set(this.model, "goodsId", checkResult.goodsId);
        this.$refs.ruleForm.clearValidate(["worksheetId"]);
        this.getCommodityList(checkResult.goodsId);
        this.getWorksheetList(checkResult.id);
      }
    },
    // 获取入库单号
    async getProductPlanNum() {
      const res = await api.ProductPlanNum({ type: "parent", code: "RK" });
      this.$set(this.model, "acceptanceNum", res.data);
    },
    //通过id获取商品列表的数据
    async getCommodityList(id) {
      let params = {
        pageNumber: 1,
        pageSize: 10,
        id,
      };
      const res = await api.CommodityList(params);
      let result = res.data.data[0];
      this.$set(this.model, "goodsName", result.goodsName);
      this.$set(this.model, "specifications", result.specifications);
      this.$set(this.model, "goodsCode", result.goodsCode);
      this.$set(this.goodModel, "tableOption", res.data.data);
    },
    // 新增
    modalAdd() {
      this.model = {};
      this.$set(this.model, "shelfIdAndGoodsQuantityVOList", [
        { shelfId: undefined, quantity: null },
      ]);
      this.modalEdit(this.model);
    },
    // 编辑
    modalEdit(record) {
      this.resetScreenSize();
      this.visible = true;
      this.model = Object.assign({}, record);
      // this.getProductPlanNum();
      if (
        this.model.shelfIdAndGoodsQuantityVOList === null ||
        this.model.shelfIdAndGoodsQuantityVOList.length == 0
      ) {
        this.model.shelfIdAndGoodsQuantityVOList = [
          { shelfId: undefined, quantity: null },
        ];
      } else {
        let shelfIdList = [];
        this.model.shelfIdAndGoodsQuantityVOList.forEach((item) => {
          shelfIdList.push(item.shelfId);
        });
        this.getShelfPage(shelfIdList);
      }
      if (record.worksheetId == null) {
        delete this.model.worksheetId;
      }
      if (!record.id) {
        this.getWarehousingNumber();
      }
      if (record.goodsId) {
        this.getCommodityList(record.goodsId);
      }

      this.getDictFindByCode("dict.receiptType");

      this.getWareHouseList();
    },
    // 库位查询
    async getShelfPage(shelfIdList) {
      let params = { shelfIdList, findAll: 0, pageNumber: 1, pageSize: 20 };
      const res = await api.ShelfPage(params);
      this.shelfModel.tableOption = res.data.data.map((item) => {
        return { value: item.id, label: item.label };
      });
    },
    onChangeMenuType() {},
    // 关闭
    handleClose() {
      this.visible = false;
      this.model = Object.assign({});
      this.$set(this.model, "shelfIdAndGoodsQuantityVOList", [
        { shelfId: undefined, quantity: null },
      ]);
    },
    //提交验证表单
    onSubmit() {
      const that = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.handleSubmit();
        } else {
          return false;
        }
      });
    },

    async handleSubmit() {
      if (this.title === "编辑") {
        this.$set(this.model, "shelfNames", this.model.shelfNames.toString());
      }

      if (this.model.receiptTypeName !== "生产入库") {
        this.model.worksheetId = null;
      }
      let res;
      this.confirmLoading = true;
      if (this.model.id) {
        res = await api.WarehousingEdit(this.model); //修改
      } else {
        res = await api.WarehousingAdd(this.model); //新增
      }
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      this.$message.success(res.message);
      this.confirmLoading = false;
      this.$emit("ok");
      this.visible = false;
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 1677;
      }
    },
    //仓库
    async getWareHouseList() {
      var params = { pageNumber: 1, pageSize: 999999 };
      const res = await api.wareHousePage(params);
      this.wareHouseList = res.data.data.map((item) => {
        return {
          value: item.id,
          label: item.wareHouseName,
          type: res.data.type,
          isLeaf: false,
        };
      });
    },

    // 异步加载数据
    async loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      let { type, value, id } = targetOption;
      targetOption.loading = true;
      // 货区
      if (type === "wareHouse") {
        targetOption.children = await this.getShelfAreaCargo(value);
        targetOption.loading = false;
      }
      // 货架
      if (type === "stockArea") {
        targetOption.children = await this.getShelfAreaRemainList(value);
        targetOption.loading = false;
      }
      // 库位
      if (type === "shelfArea") {
        targetOption.children = await this.getShelfRemainList(value);
        targetOption.loading = false;
      }

      this.wareHouseList = [...this.wareHouseList];
    },
    // 级联查询（货区）
    async getShelfAreaCargo(id) {
      const res = await api.shelfAreaCargo({ id });
      let result = res.data.data;
      if (result.length > 0) {
        return result.map((item) => {
          return {
            label: `${item.serialNumber}`,
            value: item.id,
            type: res.data.type,
            isLeaf: false,
          };
        });
      }
    },
    // 级联查询 （货架）
    async getShelfAreaRemainList(id) {
      const res = await api.shelfAreaRemainList({ id });
      let result = res.data.data;
      if (result.length > 0) {
        return result.map((item) => {
          return {
            label: `${item.serialNumber}`,
            value: item.id,
            type: res.data.type,
            isLeaf: false,
          };
        });
      }
    },
    // 级联查询 （库位）
    async getShelfRemainList(id) {
      const res = await api.shelfRemainList({ id });
      let result = res.data;
      if (result.length > 0) {
        return result.map((item) => {
          return {
            label: `${item.rowLine}-${item.col}`,
            value: item.id,
          };
        });
      }
    },
    handleDepar() {
      this.$refs.selectForm.title = "选择";
      this.$refs.selectForm.modalAdd();
    },
    // 选择框点击事件
    handleReciptSelect(open, index) {
      this.current = index;
      this.$refs.Receipt.title = "库位";
      this.$refs.Receipt.modalAdd();
      if (this.model.shelfIdAndGoodsQuantityVOList.length > 0) {
        this.$refs.Receipt.selectedRowKeys = [
          this.model.shelfIdAndGoodsQuantityVOList[this.current].shelfId,
        ];
      }
    },
    // 入库回调
    ReceiptSelect(shelfId, tableOption) {
      this.model.shelfIdAndGoodsQuantityVOList[this.current].shelfId = shelfId;
      this.shelfModel.tableOption = tableOption;
      this.$refs.ruleForm.clearValidate(
        `shelfIdAndGoodsQuantityVOList[${this.current}].shelfId`
      );
      this.$refs.ruleForm.clearValidate(
        `shelfIdAndGoodsQuantityVOList[${this.current}].quantity`
      );
    },
    handleReciptChange(value) {
      this.model.shelfIdAndGoodsQuantityVOList[this.current].shelfId = value;
    },
  },
};
</script>

<style lang="less" scoped>
.shelfBox {
  display: flex;
  align-items: center;
  padding-left: 106px !important;
  .iconBox {
    margin-left: 20px;
  }
}
</style>
